package com.linghang.back.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JwtUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);
    
    @Value("${jwt.secret:linghangDefaultSecretKey12345678901234567890}")
    private String secret;
    
    @Value("${jwt.expiration:86400000}")
    private Long expiration; // 默认24小时
    
    // 生成密钥
    private Key getSigningKey() {
        byte[] keyBytes = secret.getBytes();
        return Keys.hmacShaKeyFor(keyBytes);
    }
    
    // 从token中提取用户名
    public String getUserIdFromToken(String token) {
        logger.debug("尝试从token中提取用户ID: {}", token);
        try {
            String userId = getClaimFromToken(token, Claims::getSubject);
            logger.debug("成功从token中提取到用户ID: {}", userId);
            return userId;
        } catch (Exception e) {
            logger.error("从token中提取用户ID失败: {}", e.getMessage());
            throw e;
        }
    }
    
    // 从token中提取过期时间
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }
    
    // 从token中提取指定的claim
    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }
    
    // 解析token
    private Claims getAllClaimsFromToken(String token) {
        try {
            return Jwts.parserBuilder().setSigningKey(getSigningKey()).build().parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            logger.error("Token已过期: {}", e.getMessage());
            throw e;
        } catch (UnsupportedJwtException e) {
            logger.error("不支持的Token格式: {}", e.getMessage());
            throw e;
        } catch (MalformedJwtException e) {
            logger.error("Token格式错误: {}", e.getMessage());
            throw e;
        } catch (SignatureException e) {
            logger.error("Token签名验证失败: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error("Token解析异常: {}", e.getMessage());
            throw e;
        }
    }
    
    // 检查token是否过期
    private Boolean isTokenExpired(String token) {
        try {
            final Date expiration = getExpirationDateFromToken(token);
            boolean isExpired = expiration.before(new Date());
            if (isExpired) {
                logger.debug("Token已过期，过期时间: {}", expiration);
            }
            return isExpired;
        } catch (Exception e) {
            logger.error("检查token过期时出错: {}", e.getMessage());
            throw e;
        }
    }
    
    // 生成token
    public String generateToken(String userId) {
        logger.debug("为用户ID生成token: {}", userId);
        Map<String, Object> claims = new HashMap<>();
        String token = createToken(claims, userId);
        logger.debug("成功生成token: {}", token);
        return token;
    }
    
    // 创建token
    private String createToken(Map<String, Object> claims, String subject) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration);
        logger.debug("Token有效期至: {}", expiryDate);
        
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }
    
    // 验证token
    public Boolean validateToken(String token, String userId) {
        try {
            final String tokenUserId = getUserIdFromToken(token);
            boolean isValid = (tokenUserId.equals(userId) && !isTokenExpired(token));
            logger.debug("Token验证结果: {}, token中的userId: {}, 传入的userId: {}", isValid, tokenUserId, userId);
            return isValid;
        } catch (Exception e) {
            logger.error("Token验证失败: {}", e.getMessage());
            return false;
        }
    }
} 